package zhxt.helmet.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

//实现WebSocketHandler
public class CameraResultHandler extends TextWebSocketHandler {
    //连接建立后被spring调用, 在这里获得和处理session
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从 URL 参数中获取用户 ID
        String query = session.getUri().getQuery();
        if (query != null && query.contains("userId=")) {
            int userId =Integer.parseInt(query.split("=")[1]); // 假设 URL 是 ws://localhost:8080/results-broadcast?userId=12345

            // 将用户 ID 和会话关联起来
            WebSocketSessionManager.addSession(userId, session);
            System.out.println("User " + userId + " connected with session ID: " + session.getId());
        } else {
            System.out.println("Session creat failed, User ID is required");

            // 如果没有传递用户 ID，关闭连接或记录错误
            session.close(CloseStatus.NOT_ACCEPTABLE.withReason("User ID is required"));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        System.out.println("Session closed with session ID: " + session.getId());
        WebSocketSessionManager.removeSession(session);
    }

}
